package com.bwie.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.domain.Product;
import com.bwie.service.ProductService;
import com.bwie.mapper.ProductMapper;
import com.bwie.utils.R;
import com.bwie.vo.PageInfoVo;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

/**
* @author 36167
* @description 针对表【product(商品表)】的数据库操作Service实现
* @createDate 2025-03-08 11:01:28
*/
@Service
 public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService{

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private ElasticsearchRestTemplate restTemplate;

    @Override
    public R prodlist(PageInfoVo pageInfoVo) {
        Integer pageNum=0;
        if (pageInfoVo.getPageNum()>0){
            pageNum=pageInfoVo.getPageNum()-1;
        }

        //构造分页参数
        PageRequest request=PageRequest.of(pageNum,pageInfoVo.getPageSize());


        BoolQueryBuilder builder = new BoolQueryBuilder();
        if (!StringUtils.isEmpty(pageInfoVo.getKeyWord())){
           builder.should(QueryBuilders.matchQuery("name",pageInfoVo.getKeyWord()));
        }else {
            builder.must(QueryBuilders.matchAllQuery());
        }

        HighlightBuilder hig = new HighlightBuilder();
        hig.field("name").preTags("<font colour='red'>").postTags("</font>");

        NativeSearchQueryBuilder nati = new NativeSearchQueryBuilder();
        nati.withPageable(request).withHighlightBuilder(hig).withQuery(builder);

        SearchHits<Product> search = restTemplate.search(nati.build(), Product.class);

        long total = search.getTotalHits();

        ArrayList<Product> products = new ArrayList<>();

        for (SearchHit<Product> productSearchHit : search) {
            Product content = productSearchHit.getContent();
            List<String> name = productSearchHit.getHighlightField("name");
            if (name!=null && name.size()>0){
                content.setName(name.get(0));
            }
            products.add(content);
        }
        HashMap<String,Object> map = new HashMap<>();
        map.put("total",total);
        map.put("list",products);

        return R.OK(map);
    }
}




